import { MES_XHY_ApiHost } from '@/utils/Interceptors'

export interface RoleItem {
  RolesId: number
  RoleName: string
  Status: boolean
  CreateTime: string
  PermissionIds?: number[]
  Permissions?: { PermissionsId: number; PermissionName: string }[]
}

export interface RoleQuery {
  roleName?: string
  pageIndex?: number // 从1开始
  pageSize?: number
}

export interface RoleListResponse {
  TotalCount: number
  TotalPage: number
  PageData: RoleItem[]
  code: number
  msg: string
  data: any
}

export const getRoles = async (query: RoleQuery) => {
  const params = new URLSearchParams()
  if (query.roleName) params.append('roleName', query.roleName)
  params.append('pageIndex', String(query.pageIndex ?? 1))
  params.append('pageSize', String(query.pageSize ?? 10))

  const url = `/api/Login/roles?${params.toString()}`
  const { data } = await MES_XHY_ApiHost.get<RoleListResponse>(url)
  return data
}

// 权限项
export interface PermissionItem {
  PermissionsId: number
  PermissionName: string
  Component?: string
  Superior?: number
  CreateTime?: string
}

export interface PermissionListResponse {
  TotalCount: number
  TotalPage: number
  PageData: PermissionItem[]
  code: number
  msg: string
  data: any
}

// 获取权限列表
// - 无参数：用于下拉选择，返回后端默认分页
// - 带参数：用于权限管理页的查询分页
export const getPermissions = async (query?: { PermissionName?: string; PageIndex?: number; PageSize?: number }) => {
  let url = '/api/Login/permissions'
  if (query) {
    const params = new URLSearchParams()
    if (query.PermissionName) params.append('PermissionName', query.PermissionName)
    if (query.PageIndex !== undefined) params.append('PageIndex', String(query.PageIndex))
    if (query.PageSize !== undefined) params.append('PageSize', String(query.PageSize))
    const qs = params.toString()
    if (qs) url += `?${qs}`
  }
  const { data } = await MES_XHY_ApiHost.get<PermissionListResponse>(url)
  return data
}

// 创建角色
export interface CreateRolePayload {
  RoleName: string
  Status: boolean
  PermissionIds: number[]
}

export const createRole = async (payload: CreateRolePayload) => {
  const { data } = await MES_XHY_ApiHost.post('/api/Login/createRole', payload)
  return data as { code: number; msg: string }
}

// ========== 权限新增与树查询 ==========
export interface CreatePermissionPayload {
  PermissionName: string
  Component: string
  Superior: number // 不选则传0
}

export const createPermission = async (payload: CreatePermissionPayload) => {
  const { data } = await MES_XHY_ApiHost.post('/api/Login/permissions', payload)
  return data as { code: number; msg: string }
}

export interface PermissionTreeNode {
  PermissionsId: number
  PermissionName: string
  Component: string
  Superior: number
  CreateTime?: string
  Children?: PermissionTreeNode[]
}

export const getPermissionTree = async () => {
  const { data } = await MES_XHY_ApiHost.get<{ code: number; msg: string; data: PermissionTreeNode[] }>(
    '/api/Login/permissions/by-parent'
  )
  return data
}
